package com.tsystems.clientEmployee.gui;

import java.awt.FlowLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.border.TitledBorder;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.tsysstems.clientEmployee.ClientEmployee;
import com.tsystems.entities.Station;

public class StationManagementPanel extends JPanel {

	StationTable stationTable = new StationTable();
	private static final long serialVersionUID = 6489712085149821505L;

	Logger logger = LoggerFactory.getLogger(getClass());

	public StationManagementPanel() {
		super(new GridBagLayout());

		setBorder(new TitledBorder("Управление станциями"));

		stationTable.updateTable(ClientEmployee.getInstance().viewStations());
		stationTable.setSelectListener(new ListSelectionListener() {

			public void valueChanged(ListSelectionEvent e) {

			}
		});

		add(new JScrollPane(stationTable), new GridBagConstraints(0, 0, 1, 1,
				1.0, 1.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH,
				new Insets(0, 0, 0, 0), 0, 0));
		add(createButtonPanel(), new GridBagConstraints(0, 1, 1, 1, 1.0, 0.0,
				GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL,
				new Insets(-5, 0, 0, 0), 0, 0));

	}

	public JPanel createButtonPanel() {

		JPanel result = new JPanel(new FlowLayout());
		JButton addStation = new JButton("Добавить станцию");
		addStation.addActionListener(new ActionListener() {

			public void actionPerformed(ActionEvent e) {
				Station station = AddStationPanel.showDialog(JOptionPane
						.getRootFrame());
				if (station == null) {
					return;
				}
				
				String result= ClientEmployee.getInstance().addStation(station);
				if(result==null){
					JOptionPane
					.showMessageDialog(StationManagementPanel.this,
							"Произошла внутренняя ошибка приложения, обратитесь к администратору");
				}
				if (result.equals("Станция успешно добавлена")) {
					updateTable();
				} else {
					JOptionPane
							.showMessageDialog(StationManagementPanel.this,
									result);
				}

			}
		});
		result.add(addStation);
		return result;
	}

	public void updateTable() {

		stationTable.updateTable(ClientEmployee.getInstance().viewStations());
	}
}
